package com.tangkeyon.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.tangkeyon.common.Const;
import com.tangkeyon.common.ResponseCode;
import com.tangkeyon.dao.CategoryMapper;
import com.tangkeyon.dao.ProductMapper;
import com.tangkeyon.pojo.Category;
import com.tangkeyon.pojo.Product;
import com.tangkeyon.service.ICategoryService;
import com.tangkeyon.service.IProductService;
import com.tangkeyon.util.DateTimeUtil;
import com.tangkeyon.util.PropertiesUtil;
import com.tangkeyon.vo.ProductDetailVO;
import com.tangkeyon.vo.ProductListInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: tangkeyon@gmail.com
 * @Date: 2019/5/29 14:26
 * @Version 1.0
 */
@Service("iProductService")
public class IProductServiceImpl implements IProductService {

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private ICategoryService iCategoryService;

    @Override
    public ResponseCode saveOrUpdateProduct(Product product) {
        if (product != null) {
//            主图片和副图片全部保存在subImages中因此要将字符串分割进行分开保存
            if (StringUtils.isNotBlank(product.getSubImages())) {
                String[] imageArr = product.getSubImages().split(",");
                if (imageArr.length > 0) {
                    product.setMainImage(imageArr[0]);
                }
            }
//            保存商品
            if (product.getId()==null) {
                int resultCount = productMapper.insert(product);
                if (resultCount == 0) {
                    return ResponseCode.createByErrorMessage("保存商品失败");
                }
                return ResponseCode.creatBySuccessMessage("保存商品成功");
            } else {//更新商品
                int resultCount = productMapper.updateByPrimaryKeySelective(product);
                if (resultCount == 0) {
                    return ResponseCode.createByErrorMessage("修改商品失败");
                }
                return ResponseCode.creatBySuccessMessage("修改商品成功");
            }
        } else {
            return ResponseCode.creatBySuccessMessage("参数错误");
        }
    }

    @Override
    public ResponseCode setProductStatus(Integer productId, Integer status){
        if(productId !=null && status !=null){
           Product product=new Product();
            product.setId(productId);
            product.setStatus(status);
            int resultCount = productMapper.updateByPrimaryKeySelective(product);
            if (resultCount == 0) {
                return ResponseCode.createByErrorMessage("更改状态失败");
            }
            return ResponseCode.creatBySuccessMessage("更改状态成功");
        }else{
            return  ResponseCode.createByErrorMessage("输入的参数为空");
        }
    }

    @Override
    public ResponseCode<ProductDetailVO> manageProductInfo(Integer productId) {
        if(productId !=null){
            Product product = productMapper.selectByPrimaryKey(productId);
            if(product !=null){
                //TODO 可以在mapper.xml中定义一个ResultMap，将结果直接映射到ProductDetailVO
                ProductDetailVO productDetailVO = assembleProductDetailVO(product);
                return  ResponseCode.creatBySuccess(productDetailVO);
            }
              return  ResponseCode.createByErrorMessage("为查找到对应的商品");
        }else {
            return ResponseCode.createByErrorMessage("商品的id为空，请选择商品");
        }
    }

    /**
     * 将product的相关属性赋值给ProductDetailVO
     * @param product
     * @return
     */
    private ProductDetailVO assembleProductDetailVO(Product product){
            ProductDetailVO productDetailVO=new ProductDetailVO();
//            因为是要获取商品的详细信息，所以可以将对象的属性进行全部的复制
            BeanUtils.copyProperties(product,productDetailVO);

//         ProductDetailVO中的ParentId属性来自category表
        Category category = categoryMapper.selectByPrimaryKey(product.getId());
        if(category!=null){
            productDetailVO.setParentCategoryId(category.getParentId());
        }else{
            productDetailVO.setParentCategoryId(0);
        }
           productDetailVO.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix"));

//        从数据库中查出来的time属性是Date类型的，使用jodaTime将它转化为String类型
           productDetailVO.setCreateTime(DateTimeUtil.dateToStr(product.getCreateTime()));
           productDetailVO.setUpdateTime(DateTimeUtil.dateToStr(product.getUpdateTime()));

           return productDetailVO;
    }


//    将VO集合对赋值给PageInfo对象的List属性，因为页面需要的是详细的分页信息
    @Override
    public ResponseCode<PageInfo> selectProductListByPage(int pageNum, int pageSize) {
        List<ProductListInfoVo>listInfoVos = Lists.newArrayList();
//        设置分页数据
        PageHelper.startPage(pageNum,pageSize);
        List<Product> productList = productMapper.selectProductList();
        if (productList.size()==0){
            return  ResponseCode.createByErrorMessage("获取商品列表失败");
        }

        PageInfo pageInfo = getPageInfo(listInfoVos, productList);
        return ResponseCode.creatBySuccess(pageInfo);
    }

    private ProductListInfoVo assembleProductListInfoVo(Product product){
        ProductListInfoVo productListInfoVo=new ProductListInfoVo();
//        而这里并不是所有的属性都要获取因此采用将特定的属性进行Set即可
        productListInfoVo.setId(product.getId());
        productListInfoVo.setCategoryId(product.getCategoryId());
        productListInfoVo.setName(product.getName());
        productListInfoVo.setStatus(product.getStatus());
        productListInfoVo.setPrice(product.getPrice());
        productListInfoVo.setSubtitle(product.getSubtitle());
        productListInfoVo.setMainImage(product.getMainImage());
        productListInfoVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix"));
        return productListInfoVo;
    }

    @Override
    public ResponseCode<PageInfo> searchProduct(Integer pageSize,Integer pageNum,String productName,Integer productId){
        PageHelper.startPage(pageNum,pageSize);
        List<ProductListInfoVo> productVOList=new ArrayList<>();
//        如果传入的商品名不为空就拼接字符串进行模糊查找
        if(StringUtils.isNotBlank(productName)){
//            productName=new StringBuilder().append("%"+productName+"%").toString();这样写是错的
            productName=new StringBuilder().append("%").append(productName).append("%").toString();
        }
//        此处不用对传入的参数进行非空判断
//        根据商品名和商品Id查询商品，动态sql根据参数值是否为空的情况进行动态拼接
        List<Product> productList = productMapper.selectProductByNameAndId(productName, productId);
        PageInfo pageInfo = getPageInfo(productVOList, productList);
        return  ResponseCode.creatBySuccess(pageInfo);
    }

    private PageInfo getPageInfo(List<ProductListInfoVo> productVOList, List<Product> productList) {
        for (Product anyProduct : productList) {
            ProductListInfoVo productListInfoVo = assembleProductListInfoVo(anyProduct);
            productVOList.add(productListInfoVo);
        }
        return new PageInfo(productVOList);
    }

    @Override
    public ResponseCode<ProductDetailVO> getDetail(Integer productId){
        if(productId !=null){
            Product product = productMapper.selectByPrimaryKey(productId);
            if(product !=null){
               if (product.getStatus()== Const.ProductStatus.ON_SAIL.getCode()){
                   ProductDetailVO productDetailVO = assembleProductDetailVO(product);
                   return  ResponseCode.creatBySuccess(productDetailVO);
               }
                return  ResponseCode.createByErrorMessage("商品已下架");
            }
            return  ResponseCode.createByErrorMessage("为查找到对应的商品");
        }else {
            return ResponseCode.createByErrorMessage("商品的id为空，请选择商品");
        }
    }

    @Override
    public ResponseCode<PageInfo> searchProductListByCategoryIdOrName(String keyword, Integer categoryId, Integer pageSize, Integer pageNum, String orderby){
//       如果关键词和类别id都为空返回错误
        if(StringUtils.isBlank(keyword) && categoryId==null){
            return ResponseCode.createByErrorMessage("输入的参数错误");
        }
        PageHelper.startPage(pageNum,pageSize);
        PageInfo pageInfo=new PageInfo();
        List<Integer> categoryList=Lists.newArrayList();
//        如果关键字不为空就拼接进行模糊查询
        if(StringUtils.isNotBlank(keyword)){
           keyword=new StringBuilder().append("%").append(keyword).append("%").toString();
       }
        if(categoryId !=null){
//            若找不到对应的category并且keyword为空就封装一个空的集合返回
            Category category = categoryMapper.selectByPrimaryKey(categoryId);
            if(category==null && StringUtils.isBlank(keyword)){
                List emptyList=new ArrayList();
                pageInfo.setList(emptyList);
                return ResponseCode.creatBySuccess(pageInfo);
             }
//            若根据categoryId找到了对应的category则递归找出其下所有的节点
             categoryList = iCategoryService.selectAllLevelChildCategory(categoryId).getData();
        }
//        处理排序
        if(StringUtils.isNotBlank(orderby)){
            if(Const.OrderbyStatus.PRICE_ASC_DESC.contains(orderby)){
                String[] orderByArray = orderby.split("_");
                PageHelper.orderBy(orderByArray[0]+" "+orderByArray[1]);
            }
        }
//        调用mapper的方法进行查询
        List<Product> productList = productMapper.selectProductByIdList(keyword, categoryList);
        List<ProductListInfoVo>  productListInfoVoList=Lists.newArrayList();
        for(Product productItem:productList){
            ProductListInfoVo productListInfoVo = assembleProductListInfoVo(productItem);
            productListInfoVoList.add(productListInfoVo);
        }
         pageInfo.setList(productListInfoVoList);
        return ResponseCode.creatBySuccess(pageInfo);
    }
}
